package cn.yh.springsecurity.filter;

import cn.yh.springsecurity.common.AjaxResult;
import cn.yh.springsecurity.domain.entity.LoginUser;
import cn.yh.springsecurity.utils.JWTUtils;
import cn.yh.springsecurity.utils.RedisUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//OncePerRequestFilter 确保每个请求都经过一次这个过滤器逻辑
@Component
public class JWTFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;

    //不论是否校验通过 -> 都会进入到SecurityFilterChain方法中
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (token == null) {

//            放行 -> 进入SecurityFilterChain方法中
            filterChain.doFilter(request, response);
            return;
        }

        try {
            JWT.require(Algorithm.HMAC256("kfoaejglanldf-sfsjkgnalawd")).build().verify(token);
        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("用户凭证错误");
        }

        Long userId = JWT.decode(token).getClaim("userId").asLong();
//        System.out.println("userId: " + userId);


        LoginUser loginUser = redisUtils.getCacheObject("user:" + userId);
//        System.out.println(loginUser);

        if (loginUser == null){
            throw new RuntimeException("用户凭证已过期");
        }

        // 结合Security进行校验 --> 如何获取当前登录用户信息？    ⇡
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);

        //保存用户凭证到SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        //放行
        filterChain.doFilter(request, response);


    }
}
